package com.sky.controller.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.convert.PeriodUnit;
import org.springframework.web.bind.annotation.*;

import javax.swing.*;
import java.util.List;

@Api(tags = "C端-地址簿接口")
@RestController
@RequestMapping("/user/addressBook")
@Slf4j
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    @ApiOperation("查询当前登录用户的所有地址信息")
    @GetMapping("/list")
    public Result<List<AddressBook>> list(){
        log.info("查询当前登录用户的所有地址信息...");
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseContext.getCurrentId()!=null,AddressBook::getUserId,BaseContext.getCurrentId());
        List<AddressBook> list = addressBookService.list(queryWrapper);
        return Result.success(list);
    }

    @ApiOperation("新增地址")
    @PostMapping
    public Result save(@RequestBody AddressBook addressBook){
        log.info("新增地址...");
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookService.save(addressBook);
        return Result.success();
    }

    @ApiOperation("设置默认地址")
    @PutMapping("/default")
    public Result setDefaul(@RequestBody AddressBook addressBook){
        log.info("设置默认地址...");
       addressBookService.updDefault(addressBook);
        return Result.success();
    }

    @ApiOperation("根据id查询地址")
    @GetMapping("/{id}")
    public Result<AddressBook> getAddressBookById(@PathVariable Long id){
        log.info("根据id查询地址...");
        AddressBook addressBook = addressBookService.getById(id);
        return Result.success(addressBook);
    }

    @ApiOperation("根据修改地址")
    @PutMapping
    public Result updateById(@RequestBody AddressBook addressBook){
        log.info("根据修改地址...");
        addressBookService.updateAddressBookById(addressBook);
        return Result.success();
    }

    @ApiOperation("根据id删除地址")
    @DeleteMapping
    public Result delById(Long id){
        log.info("根据id删除地址...");
        addressBookService.removeById(id);
        return Result.success();
    }

    @ApiOperation("查询默认地址")
    @GetMapping("/default")
    public Result<AddressBook> getDefaultAddress(){
        log.info("查询默认地址...");
        AddressBook addressBook=addressBookService.getDefaultAddressByUserId();
        return Result.success(addressBook);
    }
}
